#!/usr/bin/python3
# coding=utf-8
import json
import sys

###############################################################################
## 主机初始化脚本
## 主要完成以下功能
## 1、增加配置文件
## 2、下载主机初始化文件
## 3、执行主机初始化操作
###############################################################################
server_local_ip='xxx'
server_public_ip='xxx'
app_home='xxx'
server_port='xxx'
node_home=app_home+"/node"
server_home=app_home+"/server"
arg = json.loads(sys.argv[1])
host_ip = arg.get('instance')

result = {}
result['commands'] = []

cmd0 = {}
cmd0['instance'] = host_ip
mkdir_cmd = "rm -rf "+node_home+" && mkdir -p "+node_home+" && cd "+node_home
download_res_cmd = "wget -T 3 -t 1 http://`env | grep SSH_CONNECTION | awk '{print $1}' | awk -F\"=\" '{print $NF}'`:"+server_port+"/download/sysom_node_init.tar.gz"
do_check_wget = "if [ ! -e sysom_node_init.tar.gz ];then  exit 1; fi && tar -xf sysom_node_init.tar.gz && cd sysom_node_init"
do_init_conf = "echo SERVER_LOCAL_IP="+server_local_ip+" > conf"
do_init_conf = do_init_conf + " && echo SERVER_PUBLIC_IP="+server_public_ip+" >> conf"
do_init_conf = do_init_conf + " && echo SERVER_PORT="+server_port+" >> conf"
do_init_conf = do_init_conf + " && echo APP_HOME="+app_home+" >> conf"
do_init_conf = do_init_conf + " && echo SERVER_HOME="+server_home+" >> conf"
do_init_conf = do_init_conf + " && echo NODE_HOME="+node_home+" >> conf"
do_init_conf = do_init_conf + " && echo NODE_IP="+host_ip+" >> conf"
do_init_cmd = "bash -x init.sh"
cmd0['cmd'] = mkdir_cmd+" && "+download_res_cmd+" && "+do_check_wget+" && "+do_init_conf+" && "+do_init_cmd

result['commands'].append(cmd0)

data = json.dumps(result)
print(data)
